/*
	This file is part of the OdinMS Maple Story Server
    Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
		       Matthias Butz <matze@odinms.de>
		       Jan Christian Meyer <vimes@odinms.de>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation version 3 as published by
    the Free Software Foundation. You may not use, modify or distribute
    this program under any other version of the GNU Affero General Public
    License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package client.command;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.sql.PreparedStatement;
import java.util.Arrays;
import java.util.List;
import client.IItem;
import client.ISkill;
import client.Item;
import client.MapleCharacter;
import client.MapleCharacterUtil;
import client.MapleClient;
import client.MapleInventoryType;
import client.MapleJob;
import client.MaplePet;
import client.MapleStat;
import client.SkillFactory;
import java.io.File;
import java.net.InetAddress;
import java.rmi.RemoteException;
import java.util.LinkedList;
import tools.DatabaseConnection;
import net.channel.ChannelServer;
import net.channel.handler.ChangeChannelHandler;
import net.world.remote.WorldLocation;
import provider.MapleData;
import provider.MapleDataProvider;
import provider.MapleDataProviderFactory;
import provider.MapleDataTool;
import scripting.npc.NPCScriptManager;
import server.MapleInventoryManipulator;
import server.MapleItemInformationProvider;
import server.MapleOxQuiz;
import server.MapleShopFactory;
import server.MapleTrade;
import server.life.MapleLifeFactory;
import server.life.MapleMonster;
import server.maps.MapleMap;
import server.maps.MapleMapObject;
import server.maps.MapleMapObjectType;
import tools.MaplePacketCreator;
import tools.Pair;
import tools.StringUtil;

class GMCommand {
    static boolean execute(MapleClient c, String[] splitted, char heading) {
        MapleCharacter player = c.getPlayer();
        ChannelServer cserv = c.getChannelServer();
        if (splitted[0].equals("ap")) {
            player.setRemainingAp(Integer.parseInt(splitted[1]));
            player.updateSingleStat(MapleStat.AVAILABLEAP, player.getRemainingAp());
        } else if (splitted[0].equals("buffme")) {
            final int[] array = {9001000, 9101002, 9101003, 9101008, 2001002, 1101007, 1005, 2301003, 5121009, 1111002, 4111001, 4111002, 4211003, 4211005, 1321000, 2321004, 3121002};
            for (int i : array) {
                SkillFactory.getSkill(i).getEffect(SkillFactory.getSkill(i).getMaxLevel()).applyTo(player);
            }
        } else if (splitted[0].equals("chattype")) {
            player.toggleGMChat();
            player.message("You now chat in " + (player.getGMChat() ? "white." : "black."));
        } else if (splitted[0].equals("cleardrops")) {
            player.getMap().clearDrops(player, true);
        } else if (splitted[0].equals("dc")) {
            MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(splitted[1]);
            victim.getClient().disconnect();
            cserv.broadcastPacket(MaplePacketCreator.serverNotice(6, "[Notice] "+victim.getName()+" has benn D/Ced by:"+player.getName()+"."));
        } else if (splitted[0].equals("dispose")) {
            NPCScriptManager.getInstance().dispose(c);
            c.getSession().write(MaplePacketCreator.enableActions());
            player.message("Done.");
       /* } else if (splitted[0].equals("exprate")) {
            ChannelServer.getInstance(c.getChannel()).setExpRate(Integer.parseInt(splitted[1]));
            cserv.broadcastPacket(MaplePacketCreator.serverNotice(6, "Exp Rate has been changed to " + Integer.parseInt(splitted[1]) + "x."));
            for (ChannelServer cs : ChannelServer.getAllInstances()) {
                for (MapleCharacter mc : cs.getPlayerStorage().getAllCharacters()) {
                    mc.setDropExpMod();
                }
            } */
        } else if (splitted[0].equals("fame")) {
            MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(splitted[1]);
            victim.setFame(Integer.parseInt(splitted[2]));
            victim.updateSingleStat(MapleStat.FAME, victim.getFame());
        } else if (splitted[0].equals("giftnx")) {
            MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(splitted[1]);
            victim.modifyCSPoints(1, Integer.parseInt(splitted[2]));
            player.message("You Succesfuly gived " + victim.getName() + " NX!");
            victim.message(player.getName()+ " has Given you some NX!");
        } else if (splitted[0].equals("gmshop")) {
            MapleShopFactory.getInstance().getShop(1337).sendShop(c);
            player.gainMeso(+20000, true);
        } else if (splitted[0].equals("heal")) {
            player.setHpMp(30000);
        } else if (splitted[0].equals("id")) {
            try {
                BufferedReader dis = new BufferedReader(new InputStreamReader(new URL("http://www.mapletip.com/search_java.php?search_value=" + splitted[1] + "&check=true").openConnection().getInputStream()));
                String s;
                while ((s = dis.readLine()) != null) {
                    player.dropMessage(s);
                }
                dis.close();
            } catch (Exception e) {
            }
        } else if (splitted[0].equals("item") || splitted[0].equals("drop")) {
            int itemId = Integer.parseInt(splitted[1]);
            short quantity = 1;
            try {
                quantity = Short.parseShort(splitted[2]);
            } catch (Exception e) {
            }
            if (splitted[0].equals("item")) {
                if (itemId >= 5000000 && itemId < 5000065) {
                    MaplePet.createPet(itemId);
                } else {
                    MapleInventoryManipulator.addById(c, itemId, quantity, player.getName());
                }
            } else {
                IItem toDrop;
                if (MapleItemInformationProvider.getInstance().getInventoryType(itemId) == MapleInventoryType.EQUIP) {
                    toDrop = MapleItemInformationProvider.getInstance().getEquipById(itemId);
                } else {
                    toDrop = new Item(itemId, (byte) 0, (short) quantity);
                }
                c.getPlayer().getMap().spawnItemDrop(c.getPlayer(), c.getPlayer(), toDrop, c.getPlayer().getPosition(), true, true);
            }
        } else if (splitted[0].equals("job")) {
            player.changeJob(MapleJob.getById(Integer.parseInt(splitted[1])));
        } else if (splitted[0].equals("jobperson")) {
            cserv.getPlayerStorage().getCharacterByName(splitted[1]).changeJob(MapleJob.getById(Integer.parseInt(splitted[2])));
        } else if (splitted[0].equals("kill")) {
            cserv.getPlayerStorage().getCharacterByName(splitted[1]).setHpMp(0);
        } else if (splitted[0].equals("killall")) {
            List<MapleMapObject> monsters = player.getMap().getMapObjectsInRange(player.getPosition(), Double.POSITIVE_INFINITY, Arrays.asList(MapleMapObjectType.MONSTER));
            for (MapleMapObject monstermo : monsters) {
                MapleMonster monster = (MapleMonster) monstermo;
                player.getMap().killMonster(monster, player, true);
                monster.giveExpToCharacter(player, monster.getExp() * c.getPlayer().getExpMod(), true, 1);
            }
            player.message("Killed " + monsters.size() + " monsters.");
        } else if (splitted[0].equals("level")) {
            player.setLevel(Integer.parseInt(splitted[1]));
            player.gainExp(-player.getExp(), false, false);
            player.updateSingleStat(MapleStat.LEVEL, player.getLevel());
        } else if (splitted[0].equals("levelperson")) {
            MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(splitted[1]);
            victim.setLevel(Integer.parseInt(splitted[2]));
            victim.gainExp(-victim.getExp(), false, false);
            victim.updateSingleStat(MapleStat.LEVEL, victim.getLevel());
        } else if (splitted[0].equals("levelpro")) {
            while (player.getLevel() < Math.min(255, Integer.parseInt(splitted[1]))) {
                player.levelUp(false);
            }
        } else if (splitted[0].equals("levelup")) {
            player.levelUp(false);
        } else if (splitted[0].equals("startupgm") || splitted[0].equals("maxall")) {
            player.setFame(1337);
            player.setStr(32767);
            player.setDex(32767);
            player.setInt(32767);
            player.setLuk(32767);
            player.setMaxHp(30000);
            player.setMaxMp(30000);
            player.updateSingleStat(MapleStat.STR, player.getStr());
            player.updateSingleStat(MapleStat.DEX, player.getStr());
            player.updateSingleStat(MapleStat.INT, player.getStr());
            player.updateSingleStat(MapleStat.LUK, player.getStr());
            player.maxAllSkills();
            player.saveToDB(true);
            player.message("Your stats are Maxed along with ur HP and MP plus 1337 Fame, Plus Skills are all Maxed");
            cserv.broadcastPacket(MaplePacketCreator.serverNotice(6,player.getName()+" is a full and Ready GM!"));
       } else if (splitted[0].equals("getallachievements")) {
          final int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21};
            for (int i : array) {
                player.finishAchievement(i);
            }
            player.message("You just got every Achievement possible in HoldenMs");
            try {
            cserv.getWorldInterface().broadcastMessage(player.getName(),MaplePacketCreator.serverNotice(6, "[Achievement] "+player.getName()+" is a GM and Cheated and got all the achievements of HoldenMS!").getBytes());
           } catch (RemoteException e) {
            //player.getClient().getChannelServer().reconnectWorld(); toke this out because idk if i need it?
           }
      //  } else if (splitted[0].equals("mesoperson")) {
      //      cserv.getPlayerStorage().getCharacterByName(splitted[1]).gainMeso(Integer.parseInt(splitted[2]), true);
       // } else if (splitted[0].equals("mesorate")) {
      //      ChannelServer.getInstance(c.getChannel()).setMesoRate(Integer.parseInt(splitted[1]));
     //       cserv.broadcastPacket(MaplePacketCreator.serverNotice(6, "Meso Rate has been changed to " + Integer.parseInt(splitted[1]) + "x."));
        } else if (splitted[0].equals("mesos")) {
            player.gainMeso(Integer.parseInt(splitted[1]), true);
        } else if (splitted[0].equals("notice")) {
            try {
                cserv.getWorldInterface().broadcastMessage(player.getName(), MaplePacketCreator.serverNotice(6, "["+player.getName()+"] " + joinStringFrom(splitted, 1)).getBytes());
            } catch (Exception e) {
                cserv.reconnectWorld();
            }
        } else if (splitted[0].equals("worldnotice")) {
            try {
                cserv.getWorldInterface().broadcastMessage(player.getName(), MaplePacketCreator.serverNotice(6, "[Notice] " + joinStringFrom(splitted, 1)).getBytes());
            } catch (Exception e) {
                cserv.reconnectWorld();
            }
        } else if (splitted[0].equals("event")) {
            try {
                cserv.getWorldInterface().broadcastMessage(player.getName(), MaplePacketCreator.serverNotice(6, "[Event] in Channel "+c.getChannel()+ " and it's for: "+ joinStringFrom(splitted, 1)).getBytes());
            } catch (Exception e) {
                cserv.reconnectWorld();
            }
        } else if (splitted[0].equals("online")) {
            for (ChannelServer ch : ChannelServer.getAllInstances()) {
                String s = "Characters online (Channel " + ch.getChannel() + " Online: " + ch.getPlayerStorage().getAllCharacters().size() + ") : ";
                if (ch.getPlayerStorage().getAllCharacters().size() < 50) {
                    for (MapleCharacter chr : ch.getPlayerStorage().getAllCharacters()) {
                        s += MapleCharacter.makeMapleReadable(chr.getName()) + ", ";
                    }
                    player.message(s.substring(0, s.length() - 2));
                }
            }
        } else if (splitted[0].equals("ox")) {
            if (splitted[1].equals("on") && player.getMapId() == 109020001) {
                player.getMap().setOx(new MapleOxQuiz(player.getMap()));
                player.getMap().getOx().sendQuestion();
                player.getMap().setOxQuiz(true);
            } else {
                player.getMap().setOxQuiz(false);
                player.getMap().setOx(null);
            }
        } else if (splitted[0].equals("pap")) {
            player.getMap().spawnMonsterOnGroudBelow(MapleLifeFactory.getMonster(8500001), player.getPosition());
        } else if (splitted[0].equals("pianus")) {
            player.getMap().spawnMonsterOnGroudBelow(MapleLifeFactory.getMonster(8510000), player.getPosition());
        } else if (splitted[0].equalsIgnoreCase("search")) {
            if (splitted.length > 2) {
                String search = joinStringFrom(splitted, 2);
                MapleData data = null;
                MapleDataProvider dataProvider = MapleDataProviderFactory.getDataProvider(new File("wz/String.wz"));
                player.message("~Searching~ <<Type: " + splitted[1] + " | Search: " + search + ">>");
                if (!splitted[1].equalsIgnoreCase("ITEM")) {
                    if (splitted[1].equalsIgnoreCase("NPC")) {
                        data = dataProvider.getData("Npc.img");
                    } else if (splitted[1].equalsIgnoreCase("MAP")) {
                        data = dataProvider.getData("Map.img");
                    } else if (splitted[1].equalsIgnoreCase("MOB")) {
                        List<String> retMobs = new LinkedList<String>();
                        data = dataProvider.getData("Mob.img");
                        List<Pair<Integer, String>> mobPairList = new LinkedList<Pair<Integer, String>>();
                        for (MapleData mobIdData : data.getChildren()) {
                            int mobIdFromData = Integer.parseInt(mobIdData.getName());
                            String mobNameFromData = MapleDataTool.getString(mobIdData.getChildByPath("name"), "NO-NAME");
                            mobPairList.add(new Pair<Integer, String>(mobIdFromData, mobNameFromData));
                        }
                        for (Pair<Integer, String> mobPair : mobPairList) {
                            if (mobPair.getRight().toLowerCase().contains(search.toLowerCase())) {
                                retMobs.add(mobPair.getLeft() + " - " + mobPair.getRight());
                            }
                        }
                        if (retMobs != null && retMobs.size() > 0) {
                            for (String singleRetMob : retMobs) {
                                player.message(singleRetMob);
                            }
                        } else {
                            player.message("No Mob's Found");
                        }
                    } else if (splitted[1].equalsIgnoreCase("SKILL")) {
                        data = dataProvider.getData("Skill.img");
                    } else {
                        player.message("Invalid search.\nSyntax: '/search [type] [name]', where [type] is NPC, MAP, ITEM, MOB, or SKILL.");
                        return true;
                    }
                    List<Pair<Integer, String>> searchList = new LinkedList<Pair<Integer, String>>();
                    for (MapleData searchData : data.getChildren()) {
                        int searchFromData = Integer.parseInt(searchData.getName());
                        String infoFromData = splitted[1].equalsIgnoreCase("MAP") ? MapleDataTool.getString(searchData.getChildByPath("streetName"), "NO-NAME") + " - " + MapleDataTool.getString(searchData.getChildByPath("mapName"), "NO-NAME") : MapleDataTool.getString(searchData.getChildByPath("name"), "NO-NAME");
                        searchList.add(new Pair<Integer, String>(searchFromData, infoFromData));
                    }
                    for (Pair<Integer, String> searched : searchList) {
                        if (searched.getRight().toLowerCase().contains(search.toLowerCase())) {
                            player.message(searched.getLeft() + " - " + searched.getRight());
                        }
                    }
                } else {
                    for (Pair<Integer, String> itemPair : MapleItemInformationProvider.getInstance().getAllItems()) {
                        if (itemPair.getRight().toLowerCase().contains(search.toLowerCase())) {
                            player.message(itemPair.getLeft() + " - " + itemPair.getRight());
                        }
                    }
                    player.message("Search Complete.");
                }
            } else {
                player.message("Invalid search.\nSyntax: '/search [type] [name]', where [type] is NPC, MAP, ITEM, MOB, or SKILL.");
            }
        } else if (splitted[0].equals("servermessage")) {
            for (int i = 1; i <= ChannelServer.getAllInstances().size(); i++) {
                ChannelServer.getInstance(i).setServerMessage(joinStringFrom(splitted, 1));
            }
        } else if (splitted[0].equals("sp")) {
            player.setRemainingSp(Integer.parseInt(splitted[1]));
            player.updateSingleStat(MapleStat.AVAILABLESP, player.getRemainingSp());
        } else if (splitted[0].equals("unban")) {
            try {
                PreparedStatement p = DatabaseConnection.getConnection().prepareStatement("UPDATE accounts SET banned = -1 WHERE id = " + MapleCharacter.getIdByName(splitted[1]));
                p.executeUpdate();
                p.close();
            } catch (Exception e) {
                player.message("Failed to unban " + splitted[1]);
                return true;
            }
            player.message("Unbanned " + splitted[1]);
        }  else if (splitted[0].equals("jail")) {
            MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(splitted[1]);
            int mapid = 200090300;
            if (splitted.length > 2 && splitted[1].equals("2")) {
                mapid = 980000404;
                victim = cserv.getPlayerStorage().getCharacterByName(splitted[2]);
            }
            if (victim != null) {
                MapleMap target = cserv.getMapFactory().getMap(mapid);
                victim.changeMap(target, target.getPortal(0));
                player.message(victim.getName() + " was jailed!");
                cserv.broadcastPacket(MaplePacketCreator.serverNotice(6, "[Jail] "+victim.getName()+" has gotten jailed by "+player.getName()+"!"));
            } else {
                player.message(splitted[1] + " not found!");
            }
          } else if (splitted[0].equals("unjail")) {
            MapleMap target = cserv.getMapFactory().getMap(100000000);
            MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(splitted[1]);
            victim.changeMap(target, target.getPortal(0));
            cserv.broadcastPacket(MaplePacketCreator.serverNotice(6, "[Jail] "+victim.getName()+" has been released from Jail by"+player.getName()+"!"));
           } else if (splitted[0].equals("zakum")) {
            player.getMap().spawnFakeMonsterOnGroundBelow(MapleLifeFactory.getMonster(8800000), player.getPosition());
            for (int x = 8800003; x < 8800011; x++) {
                player.getMap().spawnMonsterOnGroudBelow(MapleLifeFactory.getMonster(x), player.getPosition());
            }
        } else if (splitted[0].equals("warpallhere")) {
            for (MapleCharacter mch : cserv.getPlayerStorage().getAllCharacters()) {
                if (mch.getMapId() != player.getMapId()) {
                    mch.changeMap(player.getMap(), player.getPosition());
                }
            }
            cserv.broadcastPacket(MaplePacketCreator.serverNotice(6,player.getName() +" has Warped Everyone to the map you are on!"));
       /* } else if (splitted[0].equalsIgnoreCase("!warpwholeworld")) {
                for (ChannelServer channels : cservs) {
                    for (MapleCharacter mch : channels.getPlayerStorage().getAllCharacters()) {
                        if (mch.getClient().getChannel() != c.getChannel()) {
                            ChangeChannelHandler.changeChannel(c.getChannel(), mch.getClient());
                        } // umm..nice :O
                        if (mch.getMapId() != player.getMapId()) {
                            mch.changeMap(player.getMap(), player.getPosition());
                        }
                    }
                } */ //TODO WTF!!!!!
        } else if (splitted[0].equals("warp")) {
            MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(splitted[1]);
            if (victim != null) {
                if (splitted.length == 2) {
                    MapleMap target = victim.getMap();
                    player.changeMap(target, target.findClosestSpawnpoint(victim.getPosition()));
                } else {
                    MapleMap target = ChannelServer.getInstance(c.getChannel()).getMapFactory().getMap(Integer.parseInt(splitted[2]));
                    victim.changeMap(target, target.getPortal(0));
                }
            } else {
                try {
                    victim = player;
                    WorldLocation loc = cserv.getWorldInterface().getLocation(splitted[1]);
                    if (loc != null) {
                        player.message("You will be cross-channel warped. This may take a few seconds.");
                        MapleMap target = cserv.getMapFactory().getMap(loc.map);
                        victim.cancelAllBuffs();
                        String ip = cserv.getIP(loc.channel);
                        victim.getMap().removePlayer(victim);
                        victim.setMap(target);
                        String[] socket = ip.split(":");
                        if (victim.getTrade() != null) {
                            MapleTrade.cancelTrade(player);
                        }
                        victim.saveToDB(true);
                        ChannelServer.getInstance(c.getChannel()).removePlayer(player);
                        c.updateLoginState(MapleClient.LOGIN_SERVER_TRANSITION);
                        try {
                            c.getSession().write(MaplePacketCreator.getChannelChange(InetAddress.getByName(socket[0]), Integer.parseInt(socket[1])));
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    } else {
                        MapleMap target = cserv.getMapFactory().getMap(Integer.parseInt(splitted[1]));
                        player.changeMap(target, target.getPortal(0));
                    }
                } catch (Exception e) {
                }
            }
        } else if (splitted[0].equals("warpmap")) {
            for (MapleCharacter mch : player.getMap().getCharacters()) {
                if (mch != null) {
                    MapleMap target = ChannelServer.getInstance(c.getChannel()).getMapFactory().getMap(Integer.parseInt(splitted[1]));
                    mch.changeMap(target, target.getPortal(0));
                }
            }
        } else if (splitted[0].equals("warphere")) {
            cserv.getPlayerStorage().getCharacterByName(splitted[1]).changeMap(player.getMap(), player.getMap().findClosestSpawnpoint(player.getPosition()));
        } else if (splitted[0].equals("map")) {
            MapleMap target = cserv.getMapFactory().getMap(Integer.parseInt(splitted[1]));
            c.getPlayer().changeMap(target, target.getPortal(0));
        } else if (splitted[0].equals("ban")) {
            try {
                String originalReason = StringUtil.joinStringFrom(splitted, 2);
                String reason = player.getName() + " banned " + splitted[1] + ": " + originalReason;
                MapleCharacter target = cserv.getPlayerStorage().getCharacterByName(splitted[1]);
                if (target != null) {
                    if (target.isGM() || player.gmLevel() > 2) {
                        String readableTargetName = MapleCharacterUtil.makeMapleReadable(target.getName());
                        String ip = target.getClient().getSession().getRemoteAddress().toString().split(":")[0];
                        reason += " (IP: " + ip + ")";
                        target.ban(reason,true);
                        player.message("Banned " + readableTargetName + " ipban for " + ip + " reason: " + originalReason);
                        try {
                            ChannelServer.getInstance(c.getChannel()).getWorldInterface().broadcastMessage(player.getName(), MaplePacketCreator.serverNotice(0, "[Ban] "+readableTargetName + " has been banned by: "+player.getName()+" for " + originalReason + ".").getBytes());
                        } catch (RemoteException e) {
                            cserv.reconnectWorld();
                        }
                    } else {
                       player.message("You may not ban GMs.");
                    }
                } else {
                    if (MapleCharacter.ban(splitted[1], reason, false)) {
                        player.message("Offline Banned " + splitted[1]);
                    } else {
                       player.message("Failed to ban " + splitted[1]);
                    }
                }
            } catch (NullPointerException e) {
                player.message(splitted[1] + " could not be banned.");
            }

    } else if (splitted[0].equals("!spawn")) {
            for (int i = 0; i < Math.min(getOptionalIntArg(splitted, 2, 1), 500); i++) {
                player.getMap().spawnMonsterOnGroudBelow(MapleLifeFactory.getMonster(Integer.parseInt(splitted[1])), player.getPosition());
            }
        } else {
            if (player.gmLevel() == 1) {
                player.message("GM Command " + heading + splitted[0] + " does not exist.");
            }
            return false;
        }
        return true;
    }

    static String joinStringFrom(String arr[], int start) {
        StringBuilder builder = new StringBuilder();
        for (int i = start; i < arr.length; i++) {
            builder.append(arr[i]);
            if (i != arr.length - 1) {
                builder.append(" ");
            }
        }
        return builder.toString();
    }

    public static int getOptionalIntArg(String splitted[], int position, int def) {
        if (splitted.length > position) {
            try {
                return Integer.parseInt(splitted[position]);
            } catch (NumberFormatException nfe) {
                return def;
            }
        }
        return def;
    }
}
